package com.ruoyi.market.service.sms;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.db.entity.SmsConfigInfo;
import com.ruoyi.market.model.result.SmsInfoResult;
import com.ruoyi.market.service.ISmsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WoLianSmsInfoService implements ISmsInfoService {

    @Override
    public SmsInfoResult getSmsInfo(SmsConfigInfo smsConfigInfo) {

        SmsInfoResult smsInfoResult = new SmsInfoResult();
        smsInfoResult.setPlatformName("沃联");
        smsInfoResult.setSuccess(false);
        try {
            HttpRequest httpRequest = HttpUtil.createGet(smsConfigInfo.getQueryUrl());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("sp_id", smsConfigInfo.getAccount());
            paramMap.put("password", smsConfigInfo.getSecret());

            httpRequest.form(paramMap);

            String bodyResult = httpRequest.execute().body();
            log.info("【沃联短信服务】【余额查询】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getQueryUrl(), JSON.toJSONString(paramMap), bodyResult);

            JSONObject resultJson = JSON.parseObject(bodyResult);
            Integer code = resultJson.getInteger("code");
            String msg = resultJson.getString("msg");

            smsInfoResult.setCode(String.valueOf(code));
            smsInfoResult.setMessage(msg);

            if (code >= 0) {
                JSONObject data = resultJson.getJSONObject("data");
                String balance = data.getString("balance");
                smsInfoResult.setBalance(balance);
                smsInfoResult.setSuccess(true);
            }else{
                smsInfoResult.setSuccess(false);
            }
            return smsInfoResult;
        } catch (Exception exception) {
            exception.printStackTrace();
            smsInfoResult.setCode("9999");
            smsInfoResult.setMessage(exception.getMessage());
        }
        return smsInfoResult;
    }


}
